//
//  NSString+Extension.swift
//  newshaohuo
//
//  Created by shaohuo on 2018/3/5.
//  Copyright © 2018年 shaohuo. All rights reserved.
//

import UIKit

class iTextField: UITextField {
    
    @IBInspectable var maxLength : NSInteger = 0
    //MARK:重写
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        p_setUpTextField()
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        p_setUpTextField()
    }
    //MARK:私有方法
    private func p_setUpTextField(){
        addTarget(self, action: #selector(p_textFieldDidChange(textField:)), for: UIControlEvents.editingChanged)
    }
    @objc private func p_textFieldDidChange(textField : UITextField) {
        
        if markedTextRange?.start == nil {
            let enc = CFStringConvertEncodingToNSStringEncoding(UInt32(CFStringEncodings.GB_18030_2000.rawValue))
            let data = text?.data(using: String.Encoding(rawValue: enc))
            let dataLength = (data?.count)! as Int
            print(dataLength)
            if dataLength > maxLength {
                
                let subData = data?.subdata(in: 0 ..< maxLength)
                var limitStr = String.init(data: subData!, encoding: String.Encoding(rawValue: enc))
                if limitStr == nil {
                    limitStr = String.init(data: (data?.subdata(in: 0 ..< maxLength-1))!, encoding: String.Encoding(rawValue: enc))
                    
                }
                setValue(limitStr, forKey: "text")
                
            }
            
        }
    }
}

